﻿module Mapparola.Client {

    export class LoginView extends View {

        private username: KnockoutObservable<string>;
        private password: KnockoutObservable<string>;
        private loginArgs: Mapparola.Core.LoginArgs;

        constructor(app: Mapparola.Client.App) {
            var el = $("#login-view").get(0);
            super(el, app);

            this.username = ko.observable("admin");
            this.password = ko.observable("test");
            this.loginArgs = new Mapparola.Core.LoginArgs();
        
            ko.applyBindings(this, this.viewEl);
        }

        public ActivatePage(): void {

            if (this._app.ActivePage) {
                this._app.DeactivateView(this._app.ActivePage.viewEl);
            }

            this._app.ActivePage = this;
            this._app.ActivateView(this._app.ActivePage.viewEl);
        }

        public GetCurrentAccount(): void {

            var args: Mapparola.Core.Client.AjaxRequestArgs = {
                success: (acct: Core.User) => {
                    var user = new Core.User();
                    user.Username = acct.Username;
                    user.Password = acct.Password;
                    
                    PubSub.publish("UserRetrieved", user);
                    this._app.ActivatePage(Mapparola.Client.Page.Live);

                },
                error: (jqXHR?: JQueryXHR, textStatus?: string, errorThrown?: string) => {

                    PubSub.publish("UserRetrieved", null);

                    this._app.ActivatePage(Mapparola.Client.Page.Login);
                }
            };

            this._app.RestDataStore.CurrentUser(args);
        }

        private Login(): void {

            this.loginArgs.Username = this.username();
            this.loginArgs.Password = this.password();

            var args: Mapparola.Core.Client.AjaxRequestArgs = {

                data: this.loginArgs,
                success: () => {
                    this.GetCurrentAccount();
                },
                error: (jqXHR?: JQueryXHR, textStatus?: string, errorThrown?: string) => {
                    //delete this
                    alert(errorThrown);
                }
            };

            this._app.RestDataStore.Authenticate(this.loginArgs, args);
        }
    }
}